import { GetKeyWordHistory } from '@/utils/storage';

const initialState = {
  ArtclesList: [] as ArticlesListType[],
  suggestion: [] as string[],
  Histories: GetKeyWordHistory() as string[],
};

export default function SearchReducer(
  state = initialState,
  action: ArtclesTypeAction
): typeof initialState {
  switch (action.type) {
    case 'search/SaveArticle':
      return { ...state, ArtclesList: action.payload };
    case 'search/UpdateArticle':
      return {
        ...state,
        ArtclesList: [...state.ArtclesList, ...action.payload],
      };
    case 'search/SaveSuggestion':
      return { ...state, suggestion: action.payload.filter((item) => !!item) };
    case 'search/ClearSuggestion':
      return { ...state, suggestion: [] };
    case 'search/SaveKeyWordHistory':
      return {
        ...state,
        Histories: [
          action.payload,
          /** 去重判断 */
          ...state.Histories.filter((item) => item !== action.payload),
        ],
      };
    case 'search/ClearHistory':
      return { ...state, Histories: [] };
    case 'search/ClearArticle':
      return { ...state, ArtclesList: [] };

    default:
      return state;
  }
}
export type ArticlesListType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top?: number;
  cover: {
    type: number;
    images?: string[];
  };
};

export type ArtclesTypeAction =
  | {
      type: 'search/SaveArticle';
      payload: ArticlesListType[];
    }
  | {
      type: 'search/UpdateArticle';
      payload: ArticlesListType[];
    }
  | {
      type: 'search/SaveSuggestion';
      payload: string[];
    }
  | {
      type: 'search/ClearSuggestion';
    }
  | {
      type: 'search/SaveKeyWordHistory';
      payload: string;
    }
  | {
      type: 'search/ClearHistory';
    }
  | {
      type: 'search/ClearArticle';
    };
